package com.googlecode.astoolkit {
	
	import com.googlecode.astoolkit.utils.Sitemap;
	
	import es.yporqueno.cargadores.CargadorEvent;
	import es.yporqueno.cargadores.CargadorXml;
	
	import flash.display.*;
	import flash.events.Event;

	public class AbstractMVC extends Sprite {
		
		private var _xmlPath:String;
		private var _xmlLoader:CargadorXml;

		public function AbstractMVC(xmlPath:String="") {
			super();
			_xmlPath = xmlPath;
			addEventListener(Event.ADDED_TO_STAGE, addedToStage);
		}
		
		//
		public function init(xmlPath:String):void{
			if(!stage){
				throw new Error(this + " must be added to stage before init");
				return;
			}
			
			_xmlLoader = new CargadorXml();
			_xmlLoader.addEventListener(CargadorEvent.COMPLETE, dataLoaded);
			var a:String = "";
			//if(new LocalConnection().domain == "localhost"){
				//a = "?a=" + Math.random();
			//}
			_xmlLoader.load(xmlPath + a);
		}
		
		// TODO en la implementacion de BasicSite
		protected function createModules():void{
			//
		}

		//
		private function addedToStage(e:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
			if(_xmlPath != ""){
				init(_xmlPath);
			}
		}
		
		// 
		private function dataLoaded(e:CargadorEvent):void {
			_xmlLoader.removeEventListener(CargadorEvent.COMPLETE, dataLoaded);
			if(e.exito){
				//trace("e-->" + e.target.data);
				Sitemap.getInstance().data = e.target.data;
				
				createModules();
				
			}else{
				trace("e.errorText-->" + e.errorText);
			}
			
		}
			
		
	}
}